package com.interest.modules.account.service.impl;

import com.interest.modules.account.dao.AccountMapper;
import com.interest.modules.account.entity.Account;
import com.interest.modules.account.service.AccountService;
import com.interest.base.utils.PwdUtils;
import com.interest.base.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    public int regAccount(String account, String password) {
        Account acc = accountMapper.selectByAccount(account);
        if (acc != null) {
            return -1; //账号已经存在
        }
        String salt = RandomUtils.generRandomSolt(10);

        String pwd = PwdUtils.encryPwd(password, salt);
        acc = new Account();
        acc.setAccount(account);
        acc.setPassword(pwd);
        acc.setSalt(salt);
        accountMapper.insert(acc);
        return 0;
    }

    public boolean delAccount(String account) {
        return accountMapper.deleteAccountByAccount(account) > 0;
    }

    public boolean updatePassword(String account, String password) {
        Account acc = accountMapper.selectByAccount(account);
        if (acc == null) {
            return false; //账号已经存在
        }
        String pwd = PwdUtils.encryPwd(password, acc.getSalt());
        acc = new Account();
        acc.setAccount(account);
        acc.setPassword(pwd);
        return accountMapper.updatePassword(acc) > 0;
    }

    @Override
    public int login(String account, String password) {
        Account acc = accountMapper.selectByAccount(account);
        if (acc == null) {
            return -1; //账号存在
        }
        String pwd = PwdUtils.encryPwd(password, acc.getSalt());
        if (pwd.equalsIgnoreCase(acc.getPassword())) {
            return acc.getId();
        } else {
            return -1;//用户名密码错误
        }
    }


}
